package linter.linterjava.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import linter.linterjava.POJO.DO.UserCard;
import linter.linterjava.POJO.DTO.UserCardDTO;
import linter.linterjava.service.UserCardService;
import linter.linterjava.mapper.UserCardMapper;
import linter.linterjava.utils.UploadFileUtil;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Date;

import static linter.linterjava.custom.CustomResultType.*;

/**
 * @author 北煜
 */
@Service
public class UserCardServiceImpl extends ServiceImpl<UserCardMapper, UserCard> implements UserCardService {

    @Resource
    UserCardMapper userCardMapper;

    @Override
    public UserCard getUserCardById(Long uuid) {
        return userCardMapper.selectById(uuid);
    }

    @Override
    @CacheEvict(value = "userCard", key = "#uuid")
    public String updateUserCardById(UserCardDTO userCardDTO, Long uuid) {
        UserCard userCard = new UserCard();
        Date date = new Date();
        userCard.setNickname(userCardDTO.getNickname());
        userCard.setUserIntro(userCardDTO.getUserIntro());
        userCard.setBirthday(userCardDTO.getBirthday());
        userCard.setAddress(userCardDTO.getAddress());
        userCard.setSex(userCardDTO.getSex());
        userCard.setUpdataTime(date);
        MultipartFile file = userCardDTO.getFile();

        if (file != null && !file.isEmpty()) {
            String url = UploadFileUtil.uploadImageToQiniu(file, uuid, "images");
            userCard.setUserImg(url);
        } else {
            userCard.setUserImg(userCard.getUserImg());
        }

        int flag = userCardMapper.update(userCard, new QueryWrapper<UserCard>()
                .eq("user_id", uuid).eq("is_delete", 0));
        return flag != 1 ? UPDATE_ERROR : UPDATE_SUCCESS;
    }
}
